import urllib.request
import json

# 接收一个字符串作为参数
r = urllib.request.urlopen('http://httpbin.org/get')
# 读取response内容
text = r.read()
# http返回状态码和msg
print(r.status, r.reason)

# 返回的内容为json格式，直接用load函数加载
obj = json.loads(text)
print(obj)

# r.headers是HTTPMessage对象
print(r.headers)
# for k,v in r.headers._headers:
#     print('%s:%s' % (k,v))

ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:87.0) Gecko/20100101 Firefox/87.0'
# 添加自定义的头信息
req = urllib.request.Request('http://httpbin.org/user-agent')
req.add_header('User-Agent', ua)
# 接收一个urllib.request对象作为参数
r = urllib.request.urlopen(req)
resp = json.load(r)
# 打印出httpbin网站返回信息
print(resp)

# 页面需要登录才能访问时
# auth_handler = urllib.request.HTTPBasicAuthHandler()
# # add_password 方法名字为固定的,realm可以随便写
# # add_password(self, realm, uri, user, passwd):
# auth_handler.add_password(realm='httpbin auth',
#                           uri='/basic-auth/guye/123456',
#                           user='guye',
#                           passwd='123456')
# opener = urllib.request.build_opener(auth_handler)
# urllib.request.install_opener(opener)
# r = urllib.request.urlopen('http://httpbin.org') # uri上面已经定义过了，不需要写了
# print(r.read().decode('utf-8'))

# 使用GET参数
params = urllib.parse.urlencode({'spam':1, 'eggs':2, 'bacon':2})
url = 'http://httpbin.org/get?/%s' % params
with urllib.request.urlopen(url) as f:
    print(f.read().decode('utf-8'))

# 使用POST方法传递参数
data = urllib.parse.urlencode({'name':'小明', 'age':2})
data = data.encode() # 转换为字节字符串
with urllib.request.urlopen('http://httpbin.org/post', data) as f:
    print(json.load(f))


# 使用IP代理请求url 传递的是字典
proxy_handler = urllib.request.ProxyHandler({'http': '117.71.148.140'})
opener = urllib.request.build_opener(proxy_handler)
r = opener.open('http://httpbin.org/ip')
print(r.read())
